package com.example.zhihuhelpapp.service;

import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.core.app.NotificationCompat;

import com.example.zhihuhelpapp.R;
import com.example.zhihuhelpapp.activity.OrderListActivity;
import com.example.zhihuhelpapp.api.MySubscribe;
import com.example.zhihuhelpapp.bean.JDOrderResult;
import com.example.zhihuhelpapp.mvp.JingDongApiPresenter;
import com.example.zhihuhelpapp.mvp.contract.IJongDongApiContract;
import com.example.zhihuhelpapp.utils.CoreConstant;
import com.example.zhihuhelpapp.utils.LogUtils;
import com.example.zhihuhelpapp.utils.NotificationUtils;
import com.example.zhihuhelpapp.utils.SpUtils;
import com.trello.rxlifecycle.LifecycleTransformer;

import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;

/**
 * 用于后台获取订单的服务
 */
public class JingDongService extends Service implements IJongDongApiContract.IView {

    private static final int NOTIFICATION_ID = 101;

    private JingDongApiPresenter apiPresenter;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 如果API在26以上即版本为O则调用startForefround()方法启动服务
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            setForegroundService();
        }
        // 开启轮询，一个小时轮询一次
        apiPresenter = new JingDongApiPresenter();
        apiPresenter.attachView(this);
        startLunXun();
    }

    private Subscription getOrderSubscribe;

    private void startLunXun() {
        getOrderSubscribe = Observable.interval(CoreConstant.JD_GET_ORDER_INTERVAL, TimeUnit.SECONDS)
                .subscribe(new MySubscribe<Long>() {
                    @Override
                    public void onNext(Long aLong) {
                        apiPresenter.getOrderList(System.currentTimeMillis());
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }


    /**
     * 通过通知启动服务
     */
    @TargetApi(Build.VERSION_CODES.N)
    public void setForegroundService() {
        //设定的通知渠道名称
        String channelName = "京东服务";
        //设置通知的重要程度
        int importance = NotificationManager.IMPORTANCE_LOW;
        //构建通知渠道
        NotificationChannel channel = new NotificationChannel(NotificationUtils.CHANNEL_ID, channelName, importance);
        channel.setDescription("用于接收京东订单消息");
        //在创建的通知渠道上发送通知
        Intent intent = new Intent(this, OrderListActivity.class);

        PendingIntent pendingIntent =
                PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotificationUtils.CHANNEL_ID);
        builder.setSmallIcon(R.mipmap.ic_launcher) //设置通知图标
                .setContentTitle("jd服务")//设置通知标题
                .setContentText("运行中")//设置通知内容
                .setAutoCancel(true) //用户触摸时，自动关闭
                .setContentIntent(pendingIntent)
                .setOngoing(true);//设置处于运行状态
        //向系统注册通知渠道，注册后不能改变重要性以及其他通知行为
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
        //将服务置于启动状态 NOTIFICATION_ID指的是创建的通知的ID
        startForeground(NOTIFICATION_ID, builder.build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        if (getOrderSubscribe != null && !getOrderSubscribe.isUnsubscribed()) {
            getOrderSubscribe.unsubscribe();
        }
        stopForeground(true);
        super.onDestroy();
    }

    @Override
    public void onGetOrderList(List<JDOrderResult.JdUnionOpenOrderRowQueryResponseBean.JDOrderBean.DataBean> orderList) {
        if (orderList != null && orderList.size() > 0) {
            JDOrderResult.JdUnionOpenOrderRowQueryResponseBean.JDOrderBean.DataBean orderItem = orderList.get(0);
            long orderId = orderItem.getOrderId();
            String lastOrderId = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_LAST_ORDER_ID, "");
            if (!TextUtils.isEmpty(lastOrderId) && TextUtils.equals(String.valueOf(orderId), lastOrderId)) {
                return;
            } else {
                SpUtils.getInstance().put(CoreConstant.SpConstant.KEY_LAST_ORDER_ID, String.valueOf(orderId));
            }

            // 获取订单数据以及金额
            int orderCount = 0;
            float orderMoney = 0.0f;
            for (JDOrderResult.JdUnionOpenOrderRowQueryResponseBean.JDOrderBean.DataBean dataBean : orderList) {
                if (dataBean.isValidOrder()) {
                    // 有效订单
                    orderCount += 1;
                    orderMoney += dataBean.getEstimateFee();
                }
            }

            if (orderCount>0) {
                // 通知订单信息
                String textTip = getString(R.string.order_tip_1, orderCount, String.valueOf(orderMoney));
                Intent intent = new Intent(this, OrderListActivity.class);
                NotificationUtils.send(this, intent, getString(R.string.order_tip_0), textTip);
            }
        }
    }

    @Override
    public void onNoOrder() {
    }

    @Override
    public void showError(String message) {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public <T> LifecycleTransformer<T> bind() {
        return null;
    }
}
